package com.woniuxy.shop.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.woniuxy.shop.entity.Admin;
import com.woniuxy.shop.service.AdminService;

@WebFilter("/manager/*")
public class VisitFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse)response;
		String uri = req.getRequestURI();
//		String context = req.getContextPath();

		// 判断是否登录，没登录就跳转到登陆了页面

		if (uri.endsWith("login.jsp") || uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith("captcha")
				|| uri.endsWith(".png") || uri.endsWith(".jpg") || uri.contains("v=")||uri.endsWith("notlogin.jsp")||uri.contains("/images/")) {
			chain.doFilter(request, response);
		} else if (uri.contains("Adminservlet")) {
			String opr = req.getParameter("opr");
			if ("login".equals(opr) || "logout".equals(opr) || "tologin".equals(opr)) {
				chain.doFilter(request, response);
			} else {
				sendRedirct(req, resp, uri,chain);
			}
		} else {
			sendRedirct(req, resp, uri,chain);
		}
	}
	
	public void sendRedirct(HttpServletRequest req, HttpServletResponse resp, String uri,FilterChain chain)
			throws IOException, ServletException {
		HttpSession session = req.getSession();
//		String welcome = (String) session.getAttribute("welcome");
		Admin a = (Admin) session.getAttribute("admin");
		if (a == null) {// 最后判断是否有自动登录
			Cookie[] cookies = req.getCookies();
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals("account")) {
					
					AdminService as = new AdminService();
					Admin admin;
					try {
						admin = as.getAdmin(cookie.getName());
					} catch (Exception e) {
						break;
					}
					req.getSession().setAttribute("admin", admin);
					chain.doFilter(req, resp);
					return;
				}
			}
			resp.sendRedirect("manager/notlogin.jsp");
		}else {
			chain.doFilter(req, resp);
		}
	}

}
